import { handleSubscript } from '@/utils/cart'

const state = {
	purchaseNum: 0,
	cartList: uni.getStorageSync('shoppingCart') || [],
	isAddSuccess: false,
}

const mutations = {
	ADD_CART(state, goods) {
		const cartList = state.cartList;
		let isSameGoods = false;
		console.log('旧列表',cartList)
		console.log('新列表',goods)
		for (let i = 0; i < cartList.length; i++) {
			// 购物车已有该商品
			// 判断标准：编号和规格都一样算一种商品
			// && cartList[i].styleInfo.id == goods.cartList[i].styleInfo.id/
			if(goods.styleInfo != null){
				if (cartList[i].id === goods.id && cartList[i].spec === goods.spec
				 && cartList[i].styleInfo.id == goods.styleInfo.id) {
					cartList[i].num += goods.num;
					isSameGoods = true;
					break;
				}
			}else{
				if (cartList[i].id === goods.id && cartList[i].spec === goods.spec) {
					cartList[i].num += goods.num;
					isSameGoods = true;
					break;
				}
			}
			
		}
		if(!isSameGoods) {
			cartList.push(goods);
		}
		// console.log("购物车更新成功", cartList)
		this.commit('cart/SERIALIZE_CART');
		console.log("添加成功，置为true")
		state.isAddSuccess = true;
	},
	REMOVE_CART(state) {
		state.cartList = state.cartList.filter(item => !item.selected);
		this.commit('cart/SERIALIZE_CART');
	},
	CLEAR_ABNORMAL_CART(state) {
		state.cartList = state.cartList.filter(item => !item.isEmpty && !item.isOffShelf);
		this.commit('cart/SERIALIZE_CART');
	},
	UPDATE_CART(state, newCartList) {
		state.cartList = newCartList;
	},
	SERIALIZE_CART(state) {
		uni.setStorageSync('shoppingCart', state.cartList);
		// 计算购物车选中数量
		let cartNum = 0;
		for(let goods of state.cartList) {
			if(goods.selected && !goods.isEmpty && !goods.isOffShelf) {
				cartNum += goods.num;
			}
		}
		uni.setStorageSync('cartNum', cartNum);
		if(getCurrentPages().length == 1) {
			handleSubscript();
		}
	}
}

const actions = {

	addCart({ commit, state }, goods) {
		commit('ADD_CART', goods);
	},
	removeCart({commit, state}) {
		commit('REMOVE_CART');
	},
	clearAbnormalCart({commit, state}) {
		commit('CLEAR_ABNORMAL_CART');
	},
	updateCart({ commit, state }, newCartList) {
		commit('UPDATE_CART', newCartList);
	},
	serializeCart({ commit, state }) {
		commit('SERIALIZE_CART');
	},
	handleAddSuccess(context, isSuccess) {
		context.state.isAddSuccess = isSuccess;
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}